<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Article;
use Illuminate\Http\Request;
use App\Models\Cart;
use App\Models\CaitCart;
use Illuminate\Support\Facades\Auth;

class CartController extends Controller
{
    
    public function index(Request $request)
    {
        $this->__cate_init__($request);
        $keyword = $request->keyword;
        if($request->catid == 12) {
            $where = ['status'=> 1];
        }else {
            $where = ['status' => 1,'catid'=> $request->catid];
        }
        if($keyword)
        {
            $model = Cart::where($where)->where(function ($query) use($keyword){
							$query->orWhere('company','like', "%{$keyword}%");
							$query->orWhere('content','like', "%{$keyword}%");
							$query->orWhere('fname','like', "%{$keyword}%");
						});
        }else{
            $model = Cart::where($where);
        }
		//查询关系表中的新闻
		if($request->catid !=12 && $request->catid > 0)
		{
			$data = CaitCart::where('catid', $request->catid)->get();
			
			if($data)
			{
				$ids = [];
				foreach($data as $row)
				{
					$ids[] = $row->cart_id;
				}
				 $model->orWhere(function ($query) use($ids, $keyword) {
							$query->where('status', 1)->whereIn('id', $ids)->where(function ($query1) use($keyword){
									if($keyword)
									{
										$query1->orWhere('company','like', "%{$keyword}%");
										$query1->orWhere('content','like', "%{$keyword}%");
										$query1->orWhere('fname','like', "%{$keyword}%");
									}	
											});
						});
			}
		}
		
		$pageList = $model->orderBy('id', 'desc')->paginate(15);
		
        
        $pageList->appends(['catid'=> $request->catid]);
        $pageList->appends(['keyword'=> $request->keyword]);
        $pageList->everypage = 15;
        $category = $this->category;
        return view('cart.index', compact('pageList', 'category', 'keyword'));
    }
    
    public function detail(Request $request)
    {
        $info = Article::findOrFail($request->id);
        if($Agent->isMobile())
        {
            return view('index.mobile.detail', compact('info'));
        }
        return view('index.detail', compact('info'));
    }
}


